﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace EncryptionServer.PhotoMove
{
    public partial class FrmNewMoveFile : Form
    {
        //参数
        private BLL.MovePhotoBLL BCM = new BLL.MovePhotoBLL();
        List<BLL.MovePhotoBLL.OrderMove> ListOrderMove = new List<BLL.MovePhotoBLL.OrderMove>();
        int PreviousOrderId;            //上一个完成的订单Id
        int MoveTimes = 0;              //照片不存在移动的次数(连续移动5次)

        //属性
        public int UserId { get; set; }
        Thread th;                      //移动照片，并修改状态的线程
        bool IsDoing = false;           //当前是否正在执行移动照片的操作
        bool CanMove = false;           //移动是否开始

        public FrmNewMoveFile()
        {
            InitializeComponent();
        }

        private void FrmPhotoMove_Load(object sender, EventArgs e)
        {
            //try
            //{
            //    //默认隐藏
            //    this.Visible = false;
            //    this.Hide();
            //    //实际使用时要删除
            //    //UserId = 1;

            //    ListOrderMove = BCM.GetOrderMoveInfo();
            //    gcOrderMove.DataSource = ListOrderMove;
            //    gcOrderMove.RefreshDataSource();
            //    //开始时设为正在移动照片
            //    CanMove = true;

            //    if (CanMove == true)
            //    {
            //        //修改并发控制为原始(因为在上个照片修改为并发状态时，可能由于断网状态没被修改完毕)
            //        RecoverBingFa();
            //        //修改照片不存在为原始
            //        BCM.ModifyPhotoNotExistToPhotoWaitMove();

            //        if (th != null)
            //        {
            //            th.Abort();
            //            th = null;
            //        }
            //        th = new Thread(MoveAndChangeStatus);
            //        th.Start();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    IsDoing = false;
            //    if (ex is DataException)        //数据库连接错误(断网)
            //    {
            //        lbMessage.Items.Add(ConstString.StringCS.DataExceptionString);
            //    }
            //    else
            //    {
            //        lbMessage.Items.Add(ex.Message + "(如果错误连续出现，请重启客服)");
            //    }
            //}
            BCM.ModifyPhotoNotExistToPhotoWaitMove();

            backgroundWorkerMoveFile.WorkerReportsProgress = true;
            backgroundWorkerMoveFile.WorkerSupportsCancellation = true;
        }

        #region 修改并发控制为原始(因为在上个照片修改为并发状态时，可能由于断网状态没被修改完毕)
        //修改并发控制为原始(因为在上个照片修改为并发状态时，可能由于断网状态没被修改完毕)
        public void RecoverBingFa()
        {
            try
            {
                BCM.ModifyBack(UserId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        /// <summary>
        /// 移动照片，并改变状态(在客户界面直接被调用)
        /// </summary>
        public void MoveAndChangeStatus()
        {
            try
            {
                IsDoing = true;
                //移动并修改状态
                string r1 = BCM.MovePhoto(UserId);
                //获取所有正在被移动的订单情况
                ListOrderMove = BCM.GetOrderMoveInfo();
                RefreshOrderMove rom = new RefreshOrderMove(RefreshOrder);
                this.Invoke(rom);
                //gcOrderMove.RefreshDataSource();
                if (r1 == "10")      //所有照片已移动完毕
                {
                    IsDoing = false;
                    string orderName = BCM.CompletedOrderName;
                    int orderId = BCM.CompletedOrderId;
                    if (orderId == 0 || orderId == PreviousOrderId)
                        return;
                    PreviousOrderId = orderId;
                    AddMessageDel add = new AddMessageDel(AddMessage);
                    this.Invoke(add, new object[] { orderName + " 在" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + " 移动完毕" });
                    return;
                }
                else if (r1 == "2")    //成功,就循环执行
                {
                    MoveTimes = 0;
                    if (CanMove == true)
                    {
                        MoveAndChangeStatus();
                    }
                    else
                    {
                        IsDoing = false;
                        return;
                    }
                }
                else if (r1 == "-1")
                {
                    AddMessageDel add = new AddMessageDel(AddMessage);
                    this.Invoke(add, new object[] { "订单不存在!" });
                    IsDoing = false;
                    return;
                }
                else if (r1 == "0")
                {
                    AddMessageDel add = new AddMessageDel(AddMessage);
                    this.Invoke(add, new object[] { "订单中有产品不存在!" });
                    IsDoing = false;
                    return;
                }
                else if (r1 == "1")
                {
                    AddMessageDel add = new AddMessageDel(AddMessage);
                    this.Invoke(add, new object[] { "订单中有产品还未对商户定价!" });
                    IsDoing = false;
                    return;
                }
                else      //有照片不存在
                {
                    int index = r1.LastIndexOf("|");
                    string pName = r1.Substring(0, index);
                    if (MoveTimes < 3)                      //不存在的照片连续移动5次
                    {
                        //MoveAndChangeStatus();
                        MoveTimes++;
                        IsDoing = false;
                        return;
                    }
                    int photoId = Convert.ToInt32(r1.Substring(index + 1));
                    AddMessageDel add = new AddMessageDel(AddMessage);
                    this.Invoke(add, new object[] { "“" + pName + "”不存在" });
                    //修改不存在的照片状态为PhotoNotExist
                    BCM.ModifyPhotoStatusToPhotoNotExist(photoId);          //修改不存在的照片的状态
                    IsDoing = false;
                    return;
                }
            }
            catch (Exception ex)
            {
                IsDoing = false;
                AddMessageDel add = new AddMessageDel(AddMessage);
                this.Invoke(add, new object[] { ex.Message + "(如果错误连续出现，请重启客服)" });
                //ErrorNum++;
                //if (ErrorNum > 5)
                //{
                //Manage.IsMovePhotoRun = false;
                //this.Close();       //不可控的错误次数大于5，重启本页面
                //Manage.OpenMovePhoto();
                //}
            }
        }
        /// <summary>
        /// 移动照片，并改变状态(在客户界面直接被调用)
        /// </summary>
        public void MoveAndChangeStatus2()
        {
            try
            {
                IsDoing = true;
                //移动并修改状态
                string r1 = BCM.MovePhoto(UserId);
                //获取所有正在被移动的订单情况
                ListOrderMove = BCM.GetOrderMoveInfo();
                backgroundWorkerMoveFile.ReportProgress(1, ListOrderMove);
                //RefreshOrderMove rom = new RefreshOrderMove(RefreshOrder);
                //this.Invoke(rom);
                //gcOrderMove.RefreshDataSource();
                if (r1 == "10")      //所有照片已移动完毕
                {
                    IsDoing = false;
                    string orderName = BCM.CompletedOrderName;
                    int orderId = BCM.CompletedOrderId;
                    if (orderId == 0 || orderId == PreviousOrderId)
                        return;
                    PreviousOrderId = orderId;
                    //AddMessageDel add = new AddMessageDel(AddMessage);
                    //this.Invoke(add, new object[] { orderName + " 在" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + " 移动完毕" });
                    backgroundWorkerMoveFile.ReportProgress(0, orderName + " 在" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + " 移动完毕");
                    return;
                }
                else if (r1 == "2")    //成功,就循环执行
                {
                    MoveTimes = 0;
                    if (isStop != true)
                    {
                        MoveAndChangeStatus2();
                    }
                    else
                    {
                        //IsDoing = false;
                        return;
                    }
                }
                else if (r1 == "-1")
                {
                    //AddMessageDel add = new AddMessageDel(AddMessage);
                    //this.Invoke(add, new object[] { "订单不存在!" });
                    backgroundWorkerMoveFile.ReportProgress(0, "订单不错在！");
                    IsDoing = false;
                    return;
                }
                else if (r1 == "0")
                {
                    //AddMessageDel add = new AddMessageDel(AddMessage);
                    //this.Invoke(add, new object[] { "订单中有产品不存在!" });
                    backgroundWorkerMoveFile.ReportProgress(0, "订单中有产品不存在！");
                    IsDoing = false;
                    return;
                }
                else if (r1 == "1")
                {
                    //AddMessageDel add = new AddMessageDel(AddMessage);
                    //this.Invoke(add, new object[] { "订单中有产品还未对商户定价!" });
                    backgroundWorkerMoveFile.ReportProgress(0, "订单中有产品还未对商户定价!");
                    IsDoing = false;
                    return;
                }
                else      //有照片不存在
                {
                    int index = r1.LastIndexOf("|");
                    string pName = r1.Substring(0, index);
                    if (MoveTimes < 3)                      //不存在的照片连续移动5次
                    {
                        //MoveAndChangeStatus();
                        MoveTimes++;
                        IsDoing = false;
                        return;
                    }
                    int photoId = Convert.ToInt32(r1.Substring(index + 1));
                    //AddMessageDel add = new AddMessageDel(AddMessage);
                    //this.Invoke(add, new object[] { "“" + pName + "”不存在" });
                    backgroundWorkerMoveFile.ReportProgress(0, "“" + pName + "”不存在");
                    //修改不存在的照片状态为PhotoNotExist
                    BCM.ModifyPhotoStatusToPhotoNotExist(photoId);          //修改不存在的照片的状态
                    IsDoing = false;
                    return;
                }
            }
            catch (Exception ex)
            {
                IsDoing = false;
                //AddMessageDel add = new AddMessageDel(AddMessage);
                //this.Invoke(add, new object[] { ex.Message + "(如果错误连续出现，请重启客服)" });
                backgroundWorkerMoveFile.ReportProgress(0, ex.Message+"(如果错误连续出现，请重启客服)");
                //ErrorNum++;
                //if (ErrorNum > 5)
                //{
                //Manage.IsMovePhotoRun = false;
                //this.Close();       //不可控的错误次数大于5，重启本页面
                //Manage.OpenMovePhoto();
                //}
            }
        }

        /// <summary>
        /// 时钟，每1分钟执行一次
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (CanMove == true && IsDoing == false)
                {
                    //修改并发控制为原始
                    RecoverBingFa();
                    //修改照片不存在状态为原始状态
                    //BCM.ModifyPhotoNotExistToPhotoWaitMove();
                    StartTH();
                }
            }
            catch (Exception ex)
            {
                IsDoing = false;
                //AddMessageDel add = new AddMessageDel(AddMessage);
                //this.Invoke(add, new object[] { ex.Message + "(如果错误连续出现，请重启客服)" });
                backgroundWorkerMoveFile.ReportProgress(0, ex.Message + "(如果错误连续出现，请重启客服)");
            }
        }

        delegate void RefreshOrderMove();
        delegate void AddMessageDel(string msg);
        private void RefreshOrder()
        {
            gcOrderMove.DataSource = ListOrderMove;
            gcOrderMove.RefreshDataSource();
        }
        private void AddMessage(string msg)
        {
            lbMessage.Items.Add(msg);
        }

        #region 线程执行照片移动，并修改状态
        /// <summary>
        /// 线程执行照片移动，并修改状态
        /// </summary>
        public void StartTH()
        {
            if (th != null && th.ThreadState != ThreadState.Aborted)
            {
                th.Abort();
                th = null;
            }
            th = new Thread(MoveAndChangeStatus);
            th.Start();
        }
        #endregion

        #region 双击托盘图标展开页面
        //双击托盘图标展开页面
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.Show();
        }
        #endregion

        #region 托盘图标的右键
        private void tsHuiFu_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.Show();
        }

        private void tsMin_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            this.Hide();
        }
        #endregion

        private void tsCanMove_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    if (CanMove == false)
            //    {
            //        tsCanMove.Image = Properties.Resources.stop;
            //        tsCanMove.Text = "暂停";
            //        CanMove = true;
            //        //timer1_Tick(sender, e);             //一点开始就执行移照片
            //    }
            //    else
            //    {
            //        tsCanMove.Image = Properties.Resources.start;
            //        tsCanMove.Text = "开始";
            //        CanMove = false;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //}
            try
            {
                if (isStop == false)
                {
                    tsCanMove.Image = Properties.Resources.stop;
                    tsCanMove.Text = "暂停";
                    isStop = true;
                    //timer1_Tick(sender, e);             //一点开始就执行移照片
                }
                else
                {
                    tsCanMove.Image = Properties.Resources.start;
                    tsCanMove.Text = "开始";
                    isStop = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void FrmPhotoMove_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Visible = false;
            this.Hide();
        }

        private void backgroundWorkerMoveFile_DoWork(object sender, DoWorkEventArgs e)
        {
            isMoving = true;
            //MoveAndChangeStatus2();
            //修改并发控制为原始
            RecoverBingFa();
            //修改照片不存在状态为原始状态
            //BCM.ModifyPhotoNotExistToPhotoWaitMove();
            //StartTH();
            MoveAndChangeStatus2();
        }

        private void backgroundWorkerMoveFile_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //EncryptionServer.BLL.MovePhotoBLL.OrderMove currOrderMove = (EncryptionServer.BLL.MovePhotoBLL.OrderMove)e.UserState;
            //e.UserState
            if ((e.UserState).GetType().FullName.Contains("OrderMove"))
            //if (e.ProgressPercentage == 0)
            {
                gcOrderMove.DataSource = (List<BLL.MovePhotoBLL.OrderMove>)(e.UserState);
                gcOrderMove.RefreshDataSource();
            }
            else
            {
                lbMessage.Items.Add(Convert.ToString(e.UserState));
            }
            
        }

        private void backgroundWorkerMoveFile_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            isMoving = false;
        }
        bool isMoving = false;
        bool isStop = false;
        private void timerMoveNew_Tick(object sender, EventArgs e)
        {
            try
            {
                if (isMoving == false && isStop==false)
                {
                    ////修改并发控制为原始
                    //RecoverBingFa();
                    ////修改照片不存在状态为原始状态
                    ////BCM.ModifyPhotoNotExistToPhotoWaitMove();
                    //StartTH();
                    backgroundWorkerMoveFile.RunWorkerAsync();
                }
            }
            catch (Exception ex)
            {
                IsDoing = false;
                //AddMessageDel add = new AddMessageDel(AddMessage);
                //this.Invoke(add, new object[] { ex.Message + "(如果错误连续出现，请重启客服)" });
                backgroundWorkerMoveFile.ReportProgress(0, ex.Message + "(如果错误连续出现，请重启客服)");
            }
        }
    }
}
